package com.zyt.fullcase.dao.impl;

import com.zyt.fullcase.dao.UserDao;
import com.zyt.fullcase.domain.User;
import com.zyt.fullcase.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public User getUser(String name, String password) {
        String sql = "select * from user_t where name=? and password=?";
//        List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
        try {
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), name, password);
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<User> getAllUsers() {
        String sql = "select * from user_t";
        try {
            List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
            return users;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void deleteUser(String userId) {
        String sql = "delete from user_t where id=?";
        try {
            template.update(sql, userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public User getUser(String userId) {
        String sql = "select * from user_t where id=?";
        try {
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<User
                    >(User.class), userId);
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void updateUser(User user) {
        String sql = "update user_t set name=?, age=?, gender=?, qq=?, address=? where id=?";
        template.update(sql, user.getName(), user.getAge(), user.getGender(),user.getQq(), user.getAddress(), user.getId());
    }

    @Override
    public Integer totalCount() {
        String sql = "select count(*) from user_t";
        try {
            Integer count = this.template.queryForObject(sql, Integer.class);
            return count;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<User> getUsers(Integer page, Integer limit) {
        String sql = "select * from user_t limit ?,?";
        try {
            List<User> users = this.template.query(sql, new BeanPropertyRowMapper<User>(User.class), ((page-1) * limit), limit);
            return users;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}
